<?php
declare(strict_types=1);

namespace App\AdminApi\Module\User\Service;

use App\Common\Enums\StatusEnums;
use App\Common\Model\User\TagsModel;
use Zms\AdminElementPlus\FormCreate\Form;
use Zms\AdminElementPlus\FormCreate\FormItem;
use Zms\Basics\BasicsModel;
use Zms\Basics\BasicsServe;
use Zms\Constants\Database;
use Zms\Exception\AppException;
use Zms\Exception\ValidateException;


/**
 * 用户标签
 * @method TagsModel getModel()
 */
class TagsService extends BasicsServe
{
    public static function model(): string
    {
        return TagsModel::class;
    }

    /**
     * 用户标签表单
     * @param mixed|null $id
     * @return Form
     * @throws AppException
     */
    public function tagsForm(mixed $id = null): Form
    {
        $values = [];
        if ($id) {
            /**
             * @var TagsModel $tags
             */
            $tags = $this->search(['id' => $id])->first();
            if (!$tags) {
                throw new AppException('编辑失败,标签已失效');
            }
            $rule[] = FormItem::Hidden('id', $tags->id);
            $values = [
                'name' => $tags->name, 'desc' => $tags->desc, 'sort' => $tags->sort, 'status' => (string)$tags->status
            ];
        }
        $rule[] = FormItem::Input('name', '标签名称')->clearable(true)->maxlength(20)->required('请输入标签名称');
        $rule[] = FormItem::Textarea('desc', '说明/备注')->clearable(true)->maxlength(50);
        $rule[] = FormItem::Number('sort', '排序')->placeholder('序号越大越靠前')->min(Database::INT_MIN)->max(Database::INT_MAX)->clearable(true);
        $rule[] = FormItem::Select('status', '状态', 1)->options(StatusEnums::Datas());
        return Form::create($id ? '编辑用户标签' : '添加用户标签')
            ->setRules($rule)
            ->setValues($values)
            ->setOptionFormInline(true);
    }

    /**
     * 会员标签数据字典
     * @return array{value:string,label:string}[]
     */
    public function dictionary(): array
    {
        $data = $this->search(['status' => 1])->select(['id as value', 'name as label'])->orderByRaw('sort DESC,id DESC')->get()->toArray();
        foreach ($data as &$item) {
            $item['value'] = (string)$item['value'];
        }
        return $data;
    }


    /**
     * 新增标签
     * @throws ValidateException
     */
    public function created(array $values): BasicsModel|false
    {
        if ($this->exists(['name' => $values['name']])) {
            throw new ValidateException("标签‘{$values['name']}’已存在");
        }
        return parent::created($values); // TODO: Change the autogenerated stub
    }


    /**
     * @describe 编辑标签
     * @user zlf <zms-pro@qq.com> 2025/3/10
     * @param array $data
     * @param array|string|null $where
     * @param bool $returnModel
     * @return bool|BasicsModel
     * @throws ValidateException
     * @throws AppException
     */
    public function updated(array $data, array|string|null $where = null, bool $returnModel = false): bool|BasicsModel
    {
        if ($this->exists("(`name`=? AND `id`!=?)", [$data['name'], $data['id']])) {
            throw new ValidateException("标签‘{$data['name']}’已存在");
        }
        return parent::updated($data, $where, $returnModel); // TODO: Change the autogenerated stub
    }
}